package com.tc.nio.c4;

import com.tc.util.ByteBufferUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: tianchao
 * @Date: 2022/2/5 21:54
 * @Description:
 */
@Slf4j
public class Server {
    public static void main(String[] args) throws IOException {
        // 0
        ByteBuffer buffer = ByteBuffer.allocate(16);
        //1 创建服务器
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //2 绑定监听端口
        serverSocketChannel.bind(new InetSocketAddress(8080));
        // 3建立集合
        List<SocketChannel> channels = new ArrayList<>();
        while (true){
            log.debug("connecting ....");
            // 4 accept 建立与客户端的通信 SocketChannel用来与客户端之间进行通讯
            SocketChannel socketChannel = serverSocketChannel.accept();
            log.debug("connected .... sc: {}",socketChannel);
            channels.add(socketChannel);
            for (SocketChannel channel : channels) {
                // 5 接收客户端发送的数据
                log.debug("before read...{}",channel);
                channel.read(buffer);
                buffer.flip();
                log.debug("after read...{}",channel);
                ByteBufferUtil.debugRead(buffer);
                buffer.clear();
            }
        }

    }
}
